using System;
using System.Diagnostics;
using System.Net.Sockets;
using System.Text;
using System.Runtime.InteropServices;
using System.Security;
using System.Net;
using System.Security.Permissions;

namespace FreeFlow.Client
{
	/// <summary>
	/// Debugger for XML.
	/// </summary>
	public class UdpXmlDebugger : TraceListener
	{
    /// <summary>
    /// Writes a debug message to the debugger, implements the TraceListener abstract method.
    /// </summary>
    /// <param name="message">The message to write to the debugger.</param>
		public override void WriteLine(string message)
		{
			Write(message);
		}

    /// <summary>
    /// Writes a debug message to the debugger, implements the TraceListener abstract method.
    /// </summary>
    /// <param name="message">The message to write to the debugger.</param>
    public override void Write(string message)
    {
      SendMessage(message);
    }

    /// <summary>
    /// Writes a debug message to the debugger
    /// </summary>
    /// <param name="message">The message to send to the debugger.</param>
    public static void SendMessage(string message)
    {
      if (message != null)
      {
        const int port = 6767;

        const int maxLength = 32000;
        if (message.Length > maxLength)
          message = message.Substring(0, maxLength);

        //Create the UdpClient
        using (UdpClient client = new UdpClient())
        {
          //Send DataGram
          UnicodeEncoding encode = new UnicodeEncoding();
          byte[] sendData = encode.GetBytes(message);
   
          // check we have the correct rights
          if (SecurityManager.IsGranted(new DnsPermission(PermissionState.Unrestricted)))
          {
            //Send to Server 
            client.Send(sendData, sendData.Length, "localhost", port);
          }
        }
      }
		}
	}
}
